using System;
using System.Collections.Generic;
using System.Text;

namespace csammisrun.MsnLib.Utility
{
  static class Marshal
  {
    public static int IndexOf(byte[] buffer, byte[] search, int start)
    {
      if (start + search.Length >= buffer.Length)
      {
        return -1;
      }

      if (buffer == null || search == null)
      {
        return -1;
      }

      int i, j;

      for (i = start; i < buffer.Length; i++)
      {
        for (j = 0; j < search.Length && i + j < buffer.Length; j++)
        {
          if (buffer[i + j] != search[j])
          {
            break;
          }
        }

        if (j == search.Length)
        {
          return i;
        }
      }

      return -1;
    }

    public static string EnsureCRLF(string message)
    {
      return message.Replace("\r\n", "\n").Replace("\n", "\r\n");
    }

    public static UInt32 ByteArrayToUint32(byte[] buffer, ref int index)
    {
      UInt32 retval = BitConverter.ToUInt32(buffer, index);
      index += 4;
      return retval;
    }

    public static UInt32 ByteArrayToUint32BE(byte[] buffer, ref int index)
    {
      uint retval = (uint)((buffer[index] << 24) |
                    (buffer[index + 1] << 16) |
                    (buffer[index + 2] << 8) |
                    (buffer[index + 3]));
      index += 4;
      return retval;
    }

    public static UInt64 ByteArrayToUint64(byte[] buffer, ref int index)
    {
      UInt64 retval = BitConverter.ToUInt64(buffer, index);
      index += 8;
      return retval;
    }
  }
}
